﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using Volo.Abp.Application.Dtos;
using Volo.Abp.Application.Services;
using Volo.Abp.Domain.Repositories;

namespace Acme.BookStore.Car
{
    public class MerchandiseAppService :
        CrudAppService<
            Merchandise,
            MerchandiseDto,
            int,
            PagedAndSortedResultRequestDto,
            CreateUpdateMerchandiseDto>,
        IMerchandiseAppService
    {
        public MerchandiseAppService(IRepository<Merchandise, int> repository)
            : base(repository)
        {
        }

        public async Task<List<MerchandiseDto>> GetListByInventoryTranIdAsync(int inventoryTranId)
        {
            var query = await Repository.GetQueryableAsync();
            var list = query.Where(x => x.InventoryTranId == inventoryTranId).ToList();
            return ObjectMapper.Map<List<Merchandise>, List<MerchandiseDto>>(list);
        }

        // 批量添加
        public async Task BatchCreateAsync(BatchMerchandiseDto input)
        {
            var entities = ObjectMapper.Map<List<CreateUpdateMerchandiseDto>, List<Merchandise>>(input.Items);
            foreach (var entity in entities)
            {
                await Repository.InsertAsync(entity, autoSave: true);
            }
        }

        // 批量修改
        public async Task BatchUpdateAsync(BatchMerchandiseDto input)
        {
            foreach (var dto in input.Items)
            {
                // 用业务唯一键查找
                var entity = await Repository.FirstOrDefaultAsync(x =>
                    x.InventoryTranId == dto.InventoryTranId &&
                    x.MerchandiseNo == dto.MerchandiseNo);

                if (entity != null)
                {
                    ObjectMapper.Map(dto, entity);
                    await Repository.UpdateAsync(entity, autoSave: true);
                }
                // 如果找不到，可以选择插入新数据，或者忽略
            }
        }
    }
}
